package com.zbw.controller;

import com.zbw.domain.Admin;
import com.zbw.domain.Message;
import com.zbw.domain.User;
import com.zbw.service.IMessageService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Controller
public class MessageController {

    @Resource
    private IMessageService messageService;


    @RequestMapping("/addMessage")
    public String addMessage(Model model, HttpServletRequest request) {
        //获取当前登陆人的留言信息
        User user = (User) request.getSession().getAttribute("user");
        List<Message> list = messageService.queryByUser(user.getUserName());

        model.addAttribute("messagesList", list);
        return "user/addMessage";
    }


    @RequestMapping("/adminMessage")
    public String adminMessage(Model model, HttpServletRequest request) {
        //获取当前登陆人的留言信息
        Admin user = (Admin) request.getSession().getAttribute("admin");
        List<Message> list = null;
        if ("admin".equals(user.getAdminName())) {
            list = messageService.queryByUser(null);
        } else {
            list = messageService.queryByUser(user.getAdminName());
        }
        model.addAttribute("messagesList", list);
        return "admin/adminMessage";
    }

    @RequestMapping("/mess/addMessage")
    @ResponseBody
    public String addMessageIng(Message message, HttpServletRequest request) {
        //获取当前登陆人的留言信息
        Message message1 = new Message();
        User user = (User) request.getSession().getAttribute("user");
        message1.setText(message.getText());
        message1.setAddUser(user.getUserName());
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        message1.setTime(format.format(date));
        message1.setAdminUser("");
        message1.setAdminText("");
        message1.setReTime(null);
        messageService.insertMsg(message1);
        return "true";
    }


    @RequestMapping("/add/adminMessage")
    @ResponseBody
    public String adminMessageIng(Message message, HttpServletRequest request) {
        //获取当前登陆人的留言信息
        Message message1 = new Message();
        Admin user = (Admin) request.getSession().getAttribute("admin");
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        message1.setId(message.getId());
        message1.setAdminUser(user.getAdminName());
        message1.setAdminText(message.getAdminText());
        message1.setReTime(format.format(date));
        messageService.update(message1);
        return "true";
    }
}
